package com.briup.product_source.service.impl;

import com.briup.product_source.bean.ManagerAnimalExt;
import com.briup.product_source.bean.ManagerQrcode;
import com.briup.product_source.dao.ManagerAnimalMapper;
import com.briup.product_source.dao.ManagerQrcodeMapper;
import com.briup.product_source.service.AnimalService;
import com.briup.product_source.util.QRcodeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author lining
 * @Date 2023/6/26
 */
@Service
public class AnimalServiceImpl implements AnimalService {
    @Value("${image.path}")
    private String imagePath;
    @Value("${image.server}")
    private String imageServer;
    @Value("${QRcodeServer}")
    private String QRcodeServer;//二维码内容访问移动端路径


    @Autowired
    private ManagerAnimalMapper mapper;
    @Autowired
    private ManagerQrcodeMapper qrcodeMapper;

    @Override
    public PageInfo<List<ManagerAnimalExt>> findByPage(Integer pageNum, int pageSize, String aHealthy, String aGender) {
        //1.设置分页参数
        PageHelper.startPage(pageNum,pageSize,true);
        //2.执行mapper方法
        List<ManagerAnimalExt> list = mapper.findByPage(aHealthy,aGender);
        return new PageInfo(list);
    }

    @Override
    public String createQRcodeByAnimalId(String id) {
        //1.生成二维码内容
        String content = QRcodeServer+"?animalId="+id;
        //2.将二维码保存到指定的文件目录中
        String fileName = QRcodeUtil.createQRcode(content,imagePath);
        /*
            3.可以通过nginx服务器访问到的二维码路径
         */
        String url = imageServer+fileName;
        //将可以访问二维码路径保存到数据库中
        ManagerQrcode qrcode = new ManagerQrcode();
        qrcode.setqAnimalId(id);
        qrcode.setqImageUrl(url);
        ManagerQrcode code = qrcodeMapper.selectByAnimalId(id);

        if(code == null){//当第一次生成，插入
            qrcodeMapper.insert(qrcode);
        }else {//当第二次生成 修改图片访问路径
            qrcodeMapper.updateByPrimaryKey(qrcode);
        }
        //4.返回二维码返回路径
        return url;
    }
}
